package com.example.springcloud.controller;

import java.util.Date;
import java.util.List;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import com.example.springcloud.request.LoginRequest;
import com.example.springcloud.request.UserRegisterDto;
import com.ruoyi.common.annotation.Anonymous;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.swagger.annotations.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.example.springcloud.domain.Users;
import com.example.springcloud.service.IUsersService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 用户基本信息Controller
 * 
 * @author hx
 * @date 2025-02-14
 */
@RestController
@RequestMapping("/group_buy/users")
public class UsersController extends BaseController
{
    @Autowired
    private IUsersService usersService;

    /**
     * 查询用户基本信息列表
     */
    @PreAuthorize("@ss.hasPermi('group_buy:users:list')")
    @GetMapping("/list")
    public TableDataInfo list(Users users)
    {
        startPage();
        List<Users> list = usersService.selectUsersList(users);
        return getDataTable(list);
    }

    /**
     * 导出用户基本信息列表
     */
    @PreAuthorize("@ss.hasPermi('group_buy:users:export')")
    @Log(title = "用户基本信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Users users)
    {
        List<Users> list = usersService.selectUsersList(users);
        ExcelUtil<Users> util = new ExcelUtil<Users>(Users.class);
        util.exportExcel(response, list, "用户基本信息数据");
    }

    /**
     * 获取用户基本信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('group_buy:users:query')")
    @GetMapping(value = "/{userId}")
    public AjaxResult getInfo(@PathVariable("userId") Long userId)
    {
        return success(usersService.selectUsersByUserId(userId));
    }

    /**
     * 新增用户基本信息
     */
    @PreAuthorize("@ss.hasPermi('group_buy:users:add')")
    @Log(title = "用户基本信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Users users)
    {
        return toAjax(usersService.insertUsers(users));
    }

    /**
     * 修改用户基本信息
     */
    @PreAuthorize("@ss.hasPermi('group_buy:users:edit')")
    @Log(title = "用户基本信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Users users)
    {
        return toAjax(usersService.updateUsers(users));
    }

    /**
     * 删除用户基本信息
     */
    @PreAuthorize("@ss.hasPermi('group_buy:users:remove')")
    @Log(title = "用户基本信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
        return toAjax(usersService.deleteUsersByUserIds(userIds));
    }

    /**
     * 登陆验证
     *
     * @param loginRequest 登录请求对象
     * @return 验证信息
     */
    // TODO 缺少密码加密
    @Anonymous
    @ResponseBody
    @RequestMapping(value = "/userLogin", produces = {"application/json;charset=utf-8"}, method = RequestMethod.POST)
    @ApiOperation(value = "用户登录接口")
    @ApiResponses({@ApiResponse(code = 200, message = "登陆成功")})
    public AjaxResult userLogin(@RequestBody LoginRequest loginRequest,
                                HttpServletResponse response) {
        System.out.println(loginRequest.getUsername());

        Users userInfo = usersService.getUserByUserName(loginRequest.getUsername());
        if (userInfo != null && userInfo.getPassword().equals(loginRequest.getUserPassword())) {
            userInfo.setPassword(null); // 登陆成功后不返回password字段

            // 生成 Token
            String token = generateToken(userInfo);

            // 将 Token 存储在 Cookie 中
            Cookie cookie = new Cookie("token", token);
            cookie.setHttpOnly(true);
            response.addCookie(cookie);
//            System.out.println(token);
//            System.out.println(cookie);

            return AjaxResult.success("登陆成功！", userInfo);
        } else if (userInfo != null && !userInfo.getPassword().equals(loginRequest.getUserPassword())) {
            return AjaxResult.success("登陆失败！", "密码错误！");
        }
        // TODO 修改返回结果为AjaxResult.error()
        // 无该用户
        return AjaxResult.error("登陆失败！", "无该用户");
    }

    private String generateToken(Users userInfo) {
        // 根据用户信息生成 token
        String token = Jwts.builder()
                .setSubject(userInfo.getUsername())
                .setExpiration(new Date(System.currentTimeMillis() + 3600000)) // 设置过期时间为1小时
                .signWith(SignatureAlgorithm.HS512, "lmy3130056596")
                .compact();
        return token;
    }

    /**
     * // 用户注册接口
     *
     * @param userRegisterDto 用户注册信息
     * @return 注册结果
     */
    @ResponseBody
    @RequestMapping(value = "/userRegister", produces = {"application/json;charset=utf-8"}, method = RequestMethod.POST)
    @ApiOperation(value = "用户注册接口")
    @ApiResponses({@ApiResponse(code = 200, message = "注册成功")})
    public AjaxResult userRegister(@RequestBody UserRegisterDto userRegisterDto) {
        // 根据用户名查询用户是否已存在
        Users existingUser = usersService.getUserByUserName(userRegisterDto.getUsername());
        if (existingUser != null) {
            return AjaxResult.error("用户名已被注册，请更换用户名");
        }
        // 创建新用户信息
        Users newUser = new Users();
        newUser.setUsername(userRegisterDto.getUsername());
        newUser.setPassword(userRegisterDto.getPassword());
        newUser.setSignature(userRegisterDto.getSignature());
        newUser.setAvatar(userRegisterDto.getAvatar());
        newUser.setNickname(userRegisterDto.getNickname());

        // 其他用户信息赋值，如头像、昵称等
//    System.out.println(newUser);
        // 调用服务层完成用户注册
        boolean success = usersService.registerUser(newUser);
        if (success) {
            return AjaxResult.success("注册成功！");
        } else {
            return AjaxResult.error("注册失败，请稍后重试");
        }
    }


    // 用户修改基本资料信息
    @Anonymous
    @ResponseBody
    @RequestMapping(value = "/userModifiesInfo", produces = {"application/json;charset=utf-8"})
    @ApiOperation(value = "修改用户信息")
    public AjaxResult userModifiesInfo(@RequestBody Users userInfo) {
        return toAjax(usersService.updateUsers(userInfo));
    }
}
